<template>
  <div id="qualityPlan">
    <Breadcrumb content="质量控制" />
    <div class="bodyContent">
      <Splitpanes class="area">
        <Pane size="10">
          <el-tree ref="leftTree" style="max-width: 600px" :data="data" :props="defaultProps" highlight-current node-key="id" :current-node-key="currentTreeNode.id" default-expand-all @node-click="handleNodeClick" />
        </Pane>
        <Pane size="90">
          <Splitpanes horizontal>
            <Pane size="50">
              <vxe-toolbar perfect>
                <template #buttons>
                  <vxe-button type="text" icon="vxe-icon-refresh" class="button-blue" content="刷新" @click="findQualityPlanList()"></vxe-button>
                  <vxe-button type="text" class="button-blue" v-if="currentTreeNode.status === 0" icon="vxe-icon-square-plus" content="新建" @click="handleAdd(-1)"></vxe-button>
                  <vxe-button type="text" icon="vxe-icon-edit" v-if="currentTreeNode.status === 0" class="button-blue" content="编辑" @click="editPlan"></vxe-button>
                  <vxe-button type="text" icon="vxe-icon-save" v-if="currentTreeNode.status === 0" class="button-blue" content="提交" @click="submitPlan(1)"></vxe-button>
                  <vxe-button type="text" icon="vxe-icon-save" v-if="currentTreeNode.status === 1" class="button-blue" content="提交" @click="submitPlan(2)"></vxe-button>
                  <vxe-button type="text" icon="vxe-icon-undo" v-if="currentTreeNode.status != 0" class="button-green" @click="submitPlan(0)" content="驳回"></vxe-button>
                  <vxe-button type="text" icon="vxe-icon-delete" v-if="currentTreeNode.status === 0" class="button-red" content="删除" @click="handleDelete"></vxe-button>
                </template>
              </vxe-toolbar>
              <div class="qualityPlanBox">
                <vxe-table ref="qualityPlanTableRef" :loading="showLoading" class="mytable-scrollbar" border align="left" height="auto" :keep-source="true" :data="qualityPlanList" :row-config="{ isCurrent: true, isHover: true }" @cell-dblclick="dbDetailModel" @current-change="currentChangeEvent" :edit-config="{ trigger: 'click', mode: 'cell', showIcon: false }" resizable show-overflow>
                  <vxe-column type="checkbox" align="center" width="26"></vxe-column>
                  <vxe-column type="seq" title="序号" align="center" width="30"></vxe-column>
                  <vxe-column field="planTitle" title="主题" min-width="80px"> </vxe-column>
                  <vxe-column field="planSource" title="来源" min-width="30px"> </vxe-column>
                  <vxe-column field="lanchUserName" title="发起人"> </vxe-column>
                  <vxe-column field="startDate" title="发起日期"> </vxe-column>
                  <vxe-column field="endDate" title="关闭日期"> </vxe-column>
                  <vxe-column field="execUserName" title="执行人"> </vxe-column>
                  <vxe-column field="audiUserName" title="审核人"> </vxe-column>
                  <vxe-column field="editUserName" title="修改人"> </vxe-column>
                  <vxe-column field="currentStageName" title="当前执行阶段"></vxe-column>
                </vxe-table>
              </div>
              <vxe-modal title="新建计划" v-model="qualityPlanModal" width="600" height="500">
                <template #default>
                  <vxe-form :data="qualityPlanForm" size="small" title-align="right" title-width="100" :rules="addSubjectsRules" class="qualityPlanFormClass" ref="qualityPlanFormRef">
                    <vxe-form-item title="主题" field="planTitle" span="24" :item-render="{}">
                      <template #default="{ data }">
                        <vxe-input v-model="data.planTitle" placeholder="请输入主题" clearable></vxe-input>
                      </template>
                    </vxe-form-item>
                    <vxe-form-item title="来源" field="planSource" span="24" :item-render="{}">
                      <template #default="{ data }">
                        <vxe-select v-model="data.planSource" placeholder="请选择来源" clearable>
                          <vxe-option value="新建" label="新建"></vxe-option>
                          <vxe-option value="导入" label="导入"></vxe-option>
                        </vxe-select>
                      </template>
                    </vxe-form-item>
                    <vxe-form-item title="发起人" field="lanchUserId" span="24" :item-render="{}">
                      <template #default="{ data }">
                        <vxe-select v-model="data.lanchUserId" placeholder="请选择发起人" clearable>
                          <vxe-option v-for="(user, index) in userList" :key="index" :value="user.id" :label="user.realname"></vxe-option>
                        </vxe-select>
                      </template>
                    </vxe-form-item>
                    <vxe-form-item title="发起日期" field="startDate" span="24" :item-render="{}">
                      <template #default="{ data }">
                        <vxe-input v-model="data.startDate" placeholder="发起时间" type="date" transfer clearable></vxe-input>
                      </template>
                    </vxe-form-item>
                    <vxe-form-item title="关闭日期" field="endDate" span="24" :item-render="{}">
                      <template #default="{ data }">
                        <vxe-input v-model="data.endDate" placeholder="关闭日期" type="date" transfer clearable></vxe-input>
                      </template>
                    </vxe-form-item>
                    <vxe-form-item title="执行人" field="execUserId" span="24" :item-render="{}">
                      <template #default="{ data }">
                        <vxe-select v-model="data.execUserId" placeholder="请选择执行人" clearable>
                          <vxe-option v-for="(user, index) in userList" :key="index" :value="user.id" :label="user.realname"></vxe-option>
                        </vxe-select>
                      </template>
                    </vxe-form-item>
                    <vxe-form-item title="审核人" field="audiUserId" span="24" :item-render="{}">
                      <template #default="{ data }">
                        <vxe-select v-model="data.audiUserId" placeholder="请选择审核人" clearable>
                          <vxe-option v-for="(user, index) in userList" :key="index" :value="user.id" :label="user.realname"></vxe-option>
                        </vxe-select>
                      </template>
                    </vxe-form-item>
                    <vxe-form-item title="修改人" field="editUserId" span="24" :item-render="{}">
                      <template #default="{ data }">
                        <vxe-select v-model="data.editUserId" placeholder="请选择修改人" clearable>
                          <vxe-option v-for="(user, index) in userList" :key="index" :value="user.id" :label="user.realname"></vxe-option>
                        </vxe-select>
                      </template>
                    </vxe-form-item>
                    <vxe-form-item title="当前执行阶段" field="currentStageName" span="24" :item-render="{}">
                      <template #default="{ data }">
                        <vxe-select v-model="data.currentStageName" placeholder="当前执行阶段" clearable>
                          <vxe-option v-for="(stageType, index) in stageTypeList" :key="index" :value="stageType.name" :label="stageType.name"></vxe-option>
                        </vxe-select>
                      </template>
                    </vxe-form-item>
                    <vxe-form-item align="center" span="24">
                      <template #default>
                        <vxe-button type="submit" status="primary" content="提交" @click="saveList()"></vxe-button>
                        <vxe-button type="reset" content="重置"></vxe-button>
                      </template>
                    </vxe-form-item>
                  </vxe-form>
                </template>
              </vxe-modal>

              <el-dialog title="计划详情" v-model="qualityPlanDetailModal" width="1200" @close="planDetailClose" class="planDetailDialog">
                <QualityPlanDetail ref="qualityPlanDetailRef"></QualityPlanDetail>
              </el-dialog>
            </Pane>

            <Pane size="50">
              <vxe-toolbar perfect>
                <template #buttons>
                  <vxe-button type="text" icon="vxe-icon-refresh" class="button-blue" content="刷新" @click="findQualityStageList()"></vxe-button>
                  <vxe-button type="text" class="button-blue" v-if="currentTreeNode.status === 0" icon="vxe-icon-square-plus" content="新建" @click="handleAddStage(-1)"></vxe-button>
                  <vxe-button type="text" icon="vxe-icon-edit" v-if="currentTreeNode.status === 0" class="button-blue" content="编辑" @click="editStage"></vxe-button>
                  <vxe-button type="text" icon="vxe-icon-delete" v-if="currentTreeNode.status === 0" class="button-red" content="删除" @click="handleStageDelete"></vxe-button>
                </template>
              </vxe-toolbar>
              <div class="qualityPlanBox">
                <vxe-table ref="qualityStageTableRef" :loading="showLoading" class="mytable-scrollbar" border align="left" height="auto" :keep-source="true" :data="qualityStageList" :row-config="{ isCurrent: true, isHover: true }" @cell-dblclick="dbStageModel" :edit-config="{ trigger: 'click', mode: 'cell', showIcon: false }" resizable show-overflow>
                  <vxe-column type="checkbox" align="center" width="26"></vxe-column>
                  <vxe-column type="seq" title="序号" align="center" width="30"> </vxe-column>
                  <vxe-column field="stageStatus" title="阶段状态" min-width="80px">
                    <template #default="{ row }">
                      {{ formatterType(row.stageStatus) }}
                    </template>
                  </vxe-column>
                  <vxe-column field="stageTypeTitle" title="执行阶段" min-width="30px"> </vxe-column>
                  <vxe-column field="stageDate" title="时间"> </vxe-column>
                  <vxe-column field="execUserName" title="执行人"> </vxe-column>
                  <vxe-column field="audiUserName" title="审核人"> </vxe-column>
                  <vxe-column field="editUserName" title="修改人"> </vxe-column>
                  <!-- <vxe-column field="attachmentPath" title="附件地址"></vxe-column> -->
                  <vxe-column title="操作" fixed="right">
                    <template #default="{ row }">
                      <vxe-button status="primary" content="历史" icon="vxe-icon-eye-fill" @click="showModifying(row)" class="viewHistoryBtn"></vxe-button>
                    </template>
                  </vxe-column>
                </vxe-table>
              </div>
              <vxe-modal title="编辑" v-model="qualityStageModal" width="600" height="400">
                <template #default>
                  <vxe-form :data="qualityStageForm" size="small" title-align="right" title-width="100" class="qualityStageFormClass">
                    <vxe-form-item title="阶段状态" field="stageStatus" span="24" :item-render="{}">
                      <template #default="{ data }">
                        <vxe-select v-model="data.stageStatus" placeholder="请选择阶段状态" clearable>
                          <vxe-option value="0" label="正常"></vxe-option>
                          <vxe-option value="1" label="异常"></vxe-option>
                        </vxe-select>
                      </template>
                    </vxe-form-item>
                    <vxe-form-item title="执行阶段" field="stageTypeId" span="24" :item-render="{}">
                      <template #default="{ data }">
                        <vxe-select v-model="data.stageTypeId" placeholder="执行阶段" clearable>
                          <vxe-option v-for="(stageType, index) in stageTypeList" :key="index" :value="stageType.id" :label="stageType.name"></vxe-option>
                        </vxe-select>
                      </template>
                    </vxe-form-item>
                    <vxe-form-item title="时间" field="stageDate" span="24" :item-render="{}">
                      <template #default="{ data }">
                        <vxe-input v-model="data.stageDate" placeholder="时间" type="datetime" transfer clearable></vxe-input>
                      </template>
                    </vxe-form-item>
                    <vxe-form-item title="执行人" field="execUserId" span="24" :item-render="{}">
                      <template #default="{ data }">
                        <vxe-select v-model="data.execUserId" placeholder="请选择执行人" clearable>
                          <vxe-option v-for="(user, index) in userList" :key="index" :value="user.id" :label="user.realname"></vxe-option>
                        </vxe-select>
                      </template>
                    </vxe-form-item>
                    <vxe-form-item title="审核人" field="audiUserId" span="24" :item-render="{}">
                      <template #default="{ data }">
                        <vxe-select v-model="data.audiUserId" placeholder="请选择审核人" clearable>
                          <vxe-option v-for="(user, index) in userList" :key="index" :value="user.id" :label="user.realname"></vxe-option>
                        </vxe-select>
                      </template>
                    </vxe-form-item>
                    <vxe-form-item title="修改人" field="editUserId" span="24" :item-render="{}">
                      <template #default="{ data }">
                        <vxe-select v-model="data.editUserId" placeholder="请选择修改人" clearable>
                          <vxe-option v-for="(user, index) in userList" :key="index" :value="user.id" :label="user.realname"></vxe-option>
                        </vxe-select>
                      </template>
                    </vxe-form-item>
                    <!-- <vxe-form-item title="附件地址" field="attachmentPath" span="24" :item-render="{}">
                      <template #default="{ data }">
                        <vxe-input v-model="data.attachmentPath" placeholder="附件地址" clearable></vxe-input>
                      </template>
                    </vxe-form-item> -->
                    <vxe-form-item align="center" span="24">
                      <template #default>
                        <vxe-button type="submit" status="primary" content="保存" @click="saveStageList()"></vxe-button>
                        <vxe-button type="reset" content="重置"></vxe-button>
                      </template>
                    </vxe-form-item> </vxe-form
                ></template>
              </vxe-modal>
              <el-dialog title="修改记录" :show-close="false" v-model="stageFileModifying" append-to-body class="dialogModifyRecordsExcel" top="6vh" :close-on-click-modal="false" style="height: 800px; width: 1500px" destroy-on-close>
                <Splitpanes class="area">
                  <Pane size="10">
                    <el-timeline>
                      <el-timeline-item v-for="(activity, index) in templates" :key="index">
                        <span class="timelineSpan" @click="showHistorys(activity.sourceFileUrl)">{{ activity.createTime }} </span></el-timeline-item
                      >
                    </el-timeline>
                  </Pane>
                  <Pane size="80">
                    <LuckyExcelForm ref="refTemplteData" style="height: 690px" class="importLuckyExcelFormDiv" />
                    <div class="dialog-footer flex right justify-end">
                      <!-- <el-button @click="submitTemplateDialog">提交</el-button> -->
                      <el-button type="primary" @click="closeModifyDialog" class="cancelBtn">取消</el-button>
                    </div>
                  </Pane>
                </Splitpanes>
              </el-dialog>
              <el-dialog title="模板设置" :show-close="false" v-model="showTemplateDialog" append-to-body class="dialogModelSetExcel" top="6vh" :close-on-click-modal="false" style="height: 800px; width: 1500px" destroy-on-close>
                <LuckyExcelForm ref="refFormData" style="height: 670px" />
                <div class="dialog-footer flex right justify-end" style="margin-top: 10px">
                  <el-button type="primary" @click="submitTemplateDialog">提交</el-button>
                  <el-button type="primary" @click="closeTemplateDialog">取消</el-button>
                </div>
              </el-dialog>
            </Pane>
          </Splitpanes>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import Breadcrumb from '@/components/Breadcrumb.vue';
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { AppStore } from '../../../stores/store';
import LuckyExcelForm from '../../../components/LuckyExcel.vue';
import QualityPlanDetail from '@/components/quality/QualityPlanDetail.vue';

let { proxy }: any = getCurrentInstance();
let store = AppStore();

interface Tree {
  id: string;
  label: string;
  status: number;
  children?: Tree[];
}
const templates = reactive([]);
const defaultProps = {
  children: 'children',
  label: 'label'
};
const data: Tree[] = reactive([]);
let currentTreeNode = reactive({
  id: '',
  status: 0,
  label: ''
});
let showLoading = ref(false);
let qualityPlanList = reactive([]);
let qualityPlanModal = ref(false);
let qualityStageModal = ref(false);
let saveLoading = ref(false);
let qualityPlanForm = reactive({
  id: null,
  planTitle: '',
  planSource: '',
  planStatus: 0,
  lanchUserId: '',
  lanchUserCode: '',
  lanchUserName: '',
  startDate: '',
  endDate: '',
  execUserId: '',
  execUserCode: '',
  execUserName: '',
  audiUserId: '',
  audiUserCode: '',
  audiUserName: '',
  editUserId: '',
  editUserCode: '',
  editUserName: '',
  currentStageId: '',
  currentStageName: '',
  planTypeId: ''
});
let addSubjectsRules: any = {
  planTitle: [
    {
      required: true,
      message: '请输入主题',
      trigger: 'blur'
    }
  ],
  planSource: [
    {
      required: true,
      message: '请输入来源',
      trigger: 'blur'
    }
  ],
  lanchUserId: [
    {
      required: true,
      message: '请输入发起人',
      trigger: 'blur'
    }
  ],
  startDate: [
    {
      required: true,
      message: '请输入发起日期',
      trigger: 'blur'
    }
  ],
  endDate: [
    {
      required: true,
      message: '请输入关闭日期',
      trigger: 'blur'
    }
  ],
  execUserId: [
    {
      required: true,
      message: '请输入执行人',
      trigger: 'blur'
    }
  ],
  audiUserId: [
    {
      required: true,
      message: '请输入审核人',
      trigger: 'blur'
    }
  ],
  editUserId: [
    {
      required: true,
      message: '请输入修改人',
      trigger: 'blur'
    }
  ],
  currentStageName: [
    {
      required: true,
      message: '请输入当前阶段',
      trigger: 'blur'
    }
  ]
};
let qualityStageForm = reactive({
  id: null,
  planId: '',
  stageStatus: 0,
  stageTypeId: '',
  stageTypeTitle: '',
  stageDate: '',
  execUserId: '',
  execUserCode: '',
  execUserName: '',
  audiUserId: '',
  audiUserCode: '',
  audiUserName: '',
  editUserId: '',
  editUserCode: '',
  editUserName: '',
  attachmentPath: ''
});
let userList = reactive([]);
const userMap = ref(new Map());
let qualityStageList = reactive([]);
let currenPlanInfo = reactive({
  id: ''
});
let qualityPlanDetailModal = ref(false);
let stageTypeList = reactive([]);
let refFormData: any = ref(null); //信息表单ref
let refTemplteData: any = ref(null);
let showTemplateDialog = ref(false);
const stageMap = ref(new Map());
let stageFileModifying = ref(false);
let currentStageRow = reactive({});
let planTypeId = ref('');
let planTypeLabel = ref('');
let qualityPlanDetailRef = ref(null);
// 方法定义区 =============================================================
onMounted(() => {
  planTypeId.value = proxy.$route.query.id;
  planTypeLabel.value = proxy.$route.query.label;
  qualityPlanForm.planTypeId = planTypeId.value;
  initTreeData();
  getUserOptions();
  findStageTypeList();
});

const handleNodeClick = (data: Tree) => {
  Object.assign(currentTreeNode, data);
  findQualityPlanList();
};
// 初始化树数据
function initTreeData() {
  data.push({
    id: planTypeId,
    label: planTypeLabel,
    status: 0,
    children: [
      {
        id: '11',
        label: '未审核计划',
        status: 0
      },
      {
        id: '22',
        label: '审核中计划',
        status: 1
      },
      {
        id: '33',
        label: '已审核计划',
        status: 2
      }
    ]
  });
  let $xtable = proxy.$refs.leftTree;
  if ($xtable) {
    proxy.$nextTick(() => {
      proxy.$refs.leftTree.setCurrentKey('11');
      handleNodeClick({
        id: '11',
        label: '未审核计划',
        status: 0
      });
    });
  }
}
// 获取用户选项
function getUserOptions() {
  const url = '/api/user/getUserInfoList';
  proxy.$http
    .get(url, {})
    .then((res: any) => {
      userList.push(...res.data);
      userList.forEach((item) => {
        userMap.value.set(item.id, item);
      });
    })
    .catch((err: any) => {
      VxeMessage('获取所有用户选项 (下拉框)失败', VxeNotifyType.error);
    });
}

// 获取计划列表
function findQualityPlanList() {
  qualityPlanList.length = 0;
  const url = '/wk/quality/plan/getQualityPlanList';
  proxy.$http
    .get(url, { params: { status: currentTreeNode.status, planTypeId: qualityPlanForm.planTypeId, userId: store.userInfo.id, isAll: store.userInfo.username === 'admin' } })
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        qualityPlanList.push(...res.data);
        currentChangeEvent({ row: qualityPlanList[0] });
        const $xTable = proxy.$refs.qualityPlanTableRef as any;
        if ($xTable) {
          $xTable.setCurrentRow(qualityPlanList[0]);
        }
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 获取阶段列表
function findQualityStageList() {
  qualityStageList.length = 0;
  const url = '/wk/quality/stage/getQualityStageList';
  proxy.$http
    .get(url, { params: { planId: currenPlanInfo.id } })
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        qualityStageList.push(...res.data);
        const $xTable = proxy.$refs.qualityStageTableRef as any;
        if ($xTable) {
          $xTable.setCurrentRow(qualityStageList[0]);
        }
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 添加
function handleAdd(row?: number) {
  qualityPlanModal.value = true;
  if (proxy.$refs.qualityPlanFormRef) {
    proxy.$refs.qualityPlanFormRef.clearValidate(); //每打开一次弹框就清除验证
  }
  Object.assign(qualityPlanForm, {});
}

function editPlan() {
  const $xTable = proxy.$refs.qualityPlanTableRef as any;
  if ($xTable) {
    let row = $xTable.getCurrentRecord();
    qualityPlanModal.value = true;
    Object.assign(qualityPlanForm, row);
  }
}

function editStage() {
  const $xTable = proxy.$refs.qualityStageTableRef as any;
  if ($xTable) {
    let row = $xTable.getCurrentRecord();
    qualityStageModal.value = true;
    Object.assign(qualityStageForm, row);
  }
}

function handleAddStage(row?: number) {
  qualityStageModal.value = true;
}

// 获取阶段类型字典
function findStageTypeList() {
  const url = '/wk/quality/stage/type/page';
  proxy.$http
    .get(url, {})
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        stageTypeList.push(...res.data);
        stageTypeList.forEach((item) => {
          stageMap.value.set(item.id, item);
        });
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

function saveList() {
  saveLoading.value = true;
  let el: any = proxy.$refs.qualityPlanFormRef;
  if (!el) return;
  el.validate((valid: any) => {
    if (valid) {
      saveLoading.value = false;
      return false;
    }
    let url = '';
    if (qualityPlanForm.id == '' || qualityPlanForm.id == null || qualityPlanForm.id == undefined) {
      url = '/wk/quality/plan/addQualityPlan';
    } else {
      url = '/wk/quality/plan/editQualityPlan';
    }
    qualityPlanForm.lanchUserCode = userMap.value.get(qualityPlanForm.lanchUserId).username;
    qualityPlanForm.lanchUserName = userMap.value.get(qualityPlanForm.lanchUserId).realname;
    qualityPlanForm.execUserCode = userMap.value.get(qualityPlanForm.execUserId).username;
    qualityPlanForm.execUserName = userMap.value.get(qualityPlanForm.execUserId).realname;
    qualityPlanForm.audiUserCode = userMap.value.get(qualityPlanForm.audiUserId).username;
    qualityPlanForm.audiUserName = userMap.value.get(qualityPlanForm.audiUserId).realname;
    qualityPlanForm.editUserCode = userMap.value.get(qualityPlanForm.editUserId).username;
    qualityPlanForm.editUserName = userMap.value.get(qualityPlanForm.editUserId).realname;
    proxy.$http
      .post(url, qualityPlanForm)
      .then((res: any) => {
        VxeMessage(res.status.msg, VxeNotifyType.success);
        findQualityPlanList();
        saveLoading.value = false;
        qualityPlanModal.value = false;
        proxy.$refs.qualityPlanFormRef.clearValidate();
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
        saveLoading.value = false;
      });
    return true;
  });
}

function saveStageList() {
  saveLoading.value = true;
  let url = '';
  if (qualityStageForm.id == '' || qualityStageForm.id == null || qualityStageForm.id == undefined) {
    url = '/wk/quality/stage/addQualityStage';
  } else {
    url = '/wk/quality/stage/editQualityStage';
  }
  qualityStageForm.planId = currenPlanInfo.id;
  qualityStageForm.execUserCode = userMap.value.get(qualityStageForm.execUserId).username;
  qualityStageForm.execUserName = userMap.value.get(qualityStageForm.execUserId).realname;
  qualityStageForm.audiUserCode = userMap.value.get(qualityStageForm.audiUserId).username;
  qualityStageForm.audiUserName = userMap.value.get(qualityStageForm.audiUserId).realname;
  qualityStageForm.editUserCode = userMap.value.get(qualityStageForm.editUserId).username;
  qualityStageForm.editUserName = userMap.value.get(qualityStageForm.editUserId).realname;
  qualityStageForm.stageTypeTitle = stageMap.value.get(qualityStageForm.stageTypeId).name;
  proxy.$http
    .post(url, qualityStageForm)
    .then((res: any) => {
      VxeMessage(res.status.msg, VxeNotifyType.success);
      findQualityStageList();
      saveLoading.value = false;
      qualityStageModal.value = false;
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
      saveLoading.value = false;
    });
}

// 删除
function handleDelete() {
  const $xTable = proxy.$refs.qualityPlanTableRef as any;
  const selectRows = $xTable.getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请先选中要删除的项', VxeNotifyType.warning);
    return;
  }
  proxy
    .$confirm('确定删除此项？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then((type) => {
      if (type === 'confirm') {
        let ids = selectRows.map((item) => item.id);
        const url = '/wk/quality/plan/deleteQualityPlan';
        proxy.$http
          .post(url, ids)
          .then((res: any) => {
            if (res.status.code === 1) {
              VxeMessage('删除成功', VxeNotifyType.success);
              findQualityPlanList();
            } else {
              VxeMessage('删除失败', VxeNotifyType.error);
            }
          })
          .catch((err) => {
            VxeMessage(err.response.data.status.msg, VxeNotifyType.error);
          });
      }
    });
}

// 删除阶段
function handleStageDelete() {
  const $xTable = proxy.$refs.qualityStageTableRef as any;
  const selectRows = $xTable.getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请先选中要删除的项', VxeNotifyType.warning);
    return;
  }
  proxy
    .$confirm('确定删除此项？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then((type) => {
      if (type === 'confirm') {
        let ids = selectRows.map((item) => item.id);
        const url = '/wk/quality/stage/deleteQualityStage';
        proxy.$http
          .post(url, ids)
          .then((res: any) => {
            if (res.status.code === 1) {
              VxeMessage('删除成功', VxeNotifyType.success);
              findQualityPlanList();
            } else {
              VxeMessage('删除失败', VxeNotifyType.error);
            }
          })
          .catch((err) => {
            VxeMessage(err.response.data.status.msg, VxeNotifyType.error);
          });
      }
    });
}

// 点击事件
function currentChangeEvent(row: any) {
  Object.assign(currenPlanInfo, row.row);
  findQualityStageList();
}

//
function dbDetailModel(row) {
  qualityPlanDetailModal.value = true;
  proxy.$nextTick(() => {
    qualityPlanDetailRef?.value?.dbDetailModel(row.row);
  });
}

// 提交计划
function submitPlan(status: number) {
  const $xTable = proxy.$refs.qualityPlanTableRef as any;
  if ($xTable) {
    let row = $xTable.getCurrentRecord();
    const url = '/wk/quality/plan/updatePlanStatus';
    proxy.$http
      .post(url, { planStatus: status, id: row.id })
      .then((res: any) => {
        if (res.status.code === 1) {
          VxeMessage('提交成功', VxeNotifyType.success);
          findQualityPlanList();
        } else {
          VxeMessage('提交失败', VxeNotifyType.error);
        }
      })
      .catch((err) => {
        VxeMessage(err.response.data.status.msg, VxeNotifyType.error);
      });
  }
}

/**
 * 点击表格当前行
 * @param row
 */
function dbStageModel(row: any) {
  showTemplateDialog.value = true;
  proxy.$nextTick(() => {
    let url = '';
    if (row.row.stageFileUrl) {
      url = row.row.stageFileUrl;
    } else {
      url = row.row.fileUrl;
    }
    Object.assign(currentStageRow, row.row);
    refFormData?.value?.initExcel(url);
  });
}

// 格式化左侧试卷表格状态
function formatterType(cellValue) {
  let status = '';
  if (cellValue == '1') {
    status = '正常';
  } else {
    status = '异常';
  }
  return status;
}

/**
 * 关闭弹窗
 */
function closeTemplateDialog() {
  showTemplateDialog.value = false;
}

/**
 * 提交模板
 */
function submitTemplateDialog() {
  refFormData?.value?.submitExcel((url: string) => {
    const $xTable = proxy.$refs.qualityStageTableRef as any;
    if ($xTable) {
      let row = $xTable.getCurrentRecord();
      proxy.$http
        .post('/wk/quality/stage/updateStagePathUrl', { stageFileUrl: url, id: row.id, historyUrl: currentStageRow.stageFileUrl })
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('提交成功', VxeNotifyType.success);
            showTemplateDialog.value = false;
            findQualityStageList();
          } else {
            VxeMessage('提交失败', VxeNotifyType.error);
          }
        })
        .catch((err) => {
          VxeMessage(err.response.data.status.msg, VxeNotifyType.error);
        });
    }
  });
}

function showModifying(row: any) {
  stageFileModifying.value = true;
  getTemplates(row);
}

function showHistorys(url: any) {
  proxy.$nextTick(() => {
    refTemplteData?.value?.initExcel(url);
    refTemplteData?.value?.hiddenUpload(true);
  });
}

// 关闭弹框
function closeModifyDialog() {
  stageFileModifying.value = false;
}

// 获取模版记录列表
function getTemplates(row: any) {
  templates.length = 0;
  const url = '/wk/quality/template/record/page';
  proxy.$http
    .get(url, { params: { sourceType: 'WkQualityStageRecordType', id: row.id } })
    .then((res: any) => {
      templates.push(...res.data);
    })
    .catch((err) => {
      VxeMessage(err.response.data.status.msg, VxeNotifyType.error);
    });
}

// 关闭计划详情弹框
function planDetailClose() {
  proxy.$nextTick(() => {
    qualityPlanDetailRef?.value?.clearData();
  });
}
</script>

<style lang="scss" scoped>
#qualityPlan {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .area {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-green,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .qualityPlanBox {
        height: calc(100% - 40px);
        .viewHistoryBtn {
          border-radius: 5px;
        }
      }
      .qualityPlanFormClass,
      .qualityStageFormClass {
        :deep(.vxe-form--item) {
          margin-bottom: 10px;
        }
      }
    }
  }
}
// 操作按钮外层div
.operationsVxeBtns {
  display: flex;
  align-items: center;
}

// vxe-table表格操作按钮
:deep(.operationsVxeBtns.vxe-button.size--mini.type--button) {
  padding: 0 !important;
  margin: 1px 0 1px 5px;
  width: 22px;
  height: 22px;
  border-radius: 50%;
}
</style>

<style lang="scss">
// 模版设置弹框
.dialogModelSetExcel,
.dialogModifyRecordsExcel {
  padding: 0;

  .el-dialog__header {
    padding: 10px 20px 20px 20px;
  }
}

// 修改记录弹框
.dialogModifyRecordsExcel {
  padding: 0;

  .el-dialog__header {
    padding: 10px 20px 20px 20px;
  }

  .el-dialog__body {
    padding: 0;
    height: calc(100% - 55px);
  }

  .el-timeline {
    padding: 20px;

    // 时间轴
    .timelineSpan {
      color: #3b00ff;
      text-decoration: underline;
      cursor: pointer;
    }
  }
  .importLuckyExcelFormDiv {
    padding: 10px !important;
  }
  .cancelBtn {
    margin-right: 10px;
  }
}
</style>
